/**
 ******************************************************************************
 * @file	apd.c
 * @brief	libotdr-peripheral.so
 *
 * Copyright (C) 2017 桂林聚联科技有限公司, Inc. All Rights Reserved.
 *
 * @section Depend
 *	-# spi_mxs.ko
 *	-# spidev.ko
 *	-# libfpga-2016.so
 *
 * 2016-10-21,MenglongWu,MenglongWoo@aliyun.com
 */
#include <stdio.h>
#include <stdlib.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>

#include "proginfo.h"
#include "otdr-peripheral.h"

#define DEVICE_DEF_NAME "/dev/mxs-adc"
#define DEF_APD_CH      16

//#if CONFIG_GLINK_TR700_BOARD
#if CONFIG_PROTOCAL_TR700_SPI
#include "fpga-tr700.h"

#define DEF_SPI "/dev/spidev3.0"
static char *device_fpga = DEF_SPI;
#endif

static char *device = DEVICE_DEF_NAME;
static int   apd_ch = DEF_APD_CH;

void __attribute__((constructor)) _load_apd_env()
{
    char *env = NULL;

    env = getenv("DEVICE_APD_TEMP");
    if (env) {
	device = env;
    }
    env = getenv("DEVICE_ADC_CH");
    if (env) {
	apd_ch = atoi(env) + 20;
    }

    // 读取第一次的垃圾数据
    // int unuse;
    // getTemperature(&unuse);
}

int _adc_to_temp(int adc)
{
    // TODO ADC 值与温度的对应关系
    float vol = (adc * 3.3) / 4096.0;
    // float temp = vol * 32.05 + 17.949;
    float dat  = vol - 0.750;
    float temp = dat / 0.010 + 25;

    return (int)(temp * 1000);
}
/**
 * @brief	获取APD温度。
OTDR测试模块需要使用该接口获取APD的温度调整APD电压。
 * @param	null
 * @retval	null
 * @remarks
 * @see
 */
int iio_getTemperature(int *data)
{
    int  fd;
    char buf[4];
    int  iRes;

    char *env = NULL;
    env       = getenv("DBG_APD_TEMP");
    if (env) {
	printf("debug tempure %d\r\n", atoi(env) * 1000);
	*data = atoi(env) * 1000;
	return 0;
    }

    fd = open("/sys/bus/iio/devices/iio:device0/in_voltage9_raw", O_RDONLY);
    if (fd < 0) {
	printf("err open in_voltage9_raw\r\n");
	return -1;
    }
    iRes = read(fd, buf, 4);

    iRes = atoi(buf);
    close(fd);

    *data = _adc_to_temp(iRes);
    // printf("real tempure %d\r\n", *data);
    return 0;
}

// unuse this function ,insted by getTemperature
int imx6_get_temp_vol(float *data)
{
    int  fd, ret;
    char buf[4];

    fd = open("/sys/bus/iio/devices/iio:device0/in_voltage9_raw", O_RDONLY);
    if (fd < 0) {
	printf("err open in_voltage9_raw\r\n");
	return -1;
    }
    ret = read(fd, buf, 4);

    *data = atoi(buf);
    return 0;
}

#ifdef CONFIG_TEMP_FROM_FPGA
PROG_INFO(config, "CONFIG_TEMP_FROM_FPGA=Y");
#endif
#ifdef CONFIG_TEMP_FROM_ARM
PROG_INFO(config, "CONFIG_TEMP_FROM_ARM=Y");
#endif


#ifdef CONFIG_DS2782
PROG_INFO(config, "CONFIG_DS2782=Y");
#else
PROG_INFO(config, "CONFIG_DS2782=N");
#endif
